use reqwest::blocking;
use std::{fs::write, sync::mpsc, thread};

use super::{DownloadStatus, Downloader};
use crate::{myerror::MyErrs, url::Url};
impl Downloader {
    pub fn new(name: String, url: Url, sender: &mpsc::Sender<DownloadStatus>) -> Self {
        Downloader {
            url,
            name,
            sender: sender.clone(),
        }
    }
}
impl Downloader {
    fn in_thread(url: Url, name: String) -> Result<(), MyErrs> {
        let spon = blocking::get(url.as_string())?;
        let bytes = spon.bytes()?;
        write(name, bytes)?;
        Ok(())
    }
    pub fn start(self) {
        thread::spawn(move || {
            let sender = self.sender.clone();
            let result = Self::in_thread(self.url, self.name);
            match result {
                Ok(_) => sender.send(DownloadStatus::Success),
                Err(a) => sender.send(DownloadStatus::Fail(a)),
            }
            .unwrap();
        });
    }
}
